from django.db import models
from django.contrib.auth import get_user_model
from django.utils.timezone import timedelta
from ckeditor.fields import RichTextField, RichTextFormField
from ckeditor_uploader.fields import RichTextUploadingField

User = get_user_model()


# Create your models here.


class MovieTypeCategory(models.Model):
    """
    电影制式分类(2D,3D,IMAX)
    """
    name = models.CharField(max_length=10, unique=True, verbose_name='电影的类型', help_text='电影的类型')
    desc = models.CharField(max_length=100, blank=True, verbose_name='简介这个类型', help_text='简介这个类型')
    add_time = models.DateTimeField(auto_now=True, verbose_name='添加时间', help_text='添加时间')

    class Meta:
        verbose_name = '电影制作类型'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class MovieKindCategory(models.Model):
    """
    电影归类(动作,悬疑,科幻)
    """
    name = models.CharField(max_length=20, unique=True, verbose_name='电影归类(动作,悬疑,科幻)', help_text='电影归类(动作,悬疑,科幻)')
    desc = models.CharField(max_length=100, blank=True, verbose_name='简介这个类型', help_text='简介这个类型')
    add_time = models.DateTimeField(auto_now=True, verbose_name='添加时间', help_text='添加时间')

    class Meta:
        verbose_name = '电影归类(动作,悬疑,科幻)'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class MovieStaffCategory(models.Model):
    """
    电影职员类型(1导演、2演员、3编剧、4制片人等)
    """
    add_time = models.DateTimeField(auto_now=True, verbose_name='添加时间', help_text='添加时间')
    name = models.CharField(max_length=20, unique=True, verbose_name='职业名称', help_text='职业名称')
    desc = models.CharField(max_length=100, blank=True, verbose_name='说明', help_text='说明')

    class Meta:
        verbose_name = '电影职员类型(导演,演员)'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class MovieStaff(models.Model):
    """
    电影职员详细信息
    """
    name = models.CharField(verbose_name='演员名称', max_length=50, unique=True, help_text='演员名称')
    desc = models.TextField(max_length=500, verbose_name='简介', blank=True, help_text=True)
    type = models.ManyToManyField(MovieStaffCategory, verbose_name='职业', help_text='职业')
    add_time = models.DateTimeField(auto_now=True, verbose_name='添加时间', help_text='添加时间')

    class Meta:
        verbose_name = '电影职员详细信息'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class SubTitle(models.Model):
    name = models.CharField(max_length=20, verbose_name='电影副标题', help_text='电影副标题')

    class Meta:
        verbose_name = '电影副标题'
        verbose_name_plural = verbose_name

    def __str__(self):
        return str(self.name)


class MovieCountry(models.Model):
    """
    电影所属国家
    """
    name = models.CharField(max_length=20, verbose_name='电影所属国家', help_text='电影所属国家')
    add_time = models.DateTimeField(auto_now=True, verbose_name='添加时间', help_text='添加时间')

    class Meta:
        verbose_name = '电影所属国家'
        verbose_name_plural = verbose_name


class MovieDetail(models.Model):
    """
    电影详细信息
    """
    STATUS = (
        (1, '已上映'),
        (2, '未上映'),
        (3, '已下架'),
    )
    IS_BANNER = (
        ('1', '在首页轮播'),
        ('0', "不轮播")
    )
    name = models.CharField(max_length=80, verbose_name='电影名称', help_text='电影名称', unique=True)

    add_time = models.DateTimeField(auto_now=True, verbose_name='信息添加时间', help_text='信息添加时间')
    is_hot = models.BooleanField(default=False, verbose_name='是否是热门', help_text='是否热门')
    hot_index = models.CharField(max_length=5, default='0', verbose_name='热门中的排序', help_text='热门中的排序')
    is_new = models.BooleanField(default=False, verbose_name='是否是最新影片', help_text='是否是最新影片')
    new_index = models.CharField(max_length=5, default='0', verbose_name='最新中的排序', help_text='最新中的排序')
    on_sale_time = models.DateTimeField(auto_now=True, verbose_name='上映时间', help_text='上映时间')
    movie_brief = RichTextUploadingField(default='目前没有还有简介', max_length=500, verbose_name='电影简介', help_text='电影简介')
    kind_category = models.ManyToManyField(MovieKindCategory, verbose_name='电影归类', help_text='电影归类')
    type_category = models.ManyToManyField(MovieTypeCategory, verbose_name='电影制作类型', related_name='movie_type_category')
    status = models.IntegerField(default=2, verbose_name='上映状态', choices=STATUS, help_text='上映状态')
    banner_index = models.CharField(max_length=5, default='0', verbose_name='是否在选片的时候轮播的排序', help_text='是否在选片的时候轮播的排序')
    is_banner = models.CharField(default='0', max_length=1, choices=IS_BANNER, verbose_name='是否在展示的时候轮播(热映或即将上映)',
                                 help_text='是否在展示的时候轮播(热映或即将上映)')
    movie_length = models.CharField(max_length=5, default='120', verbose_name='影片时长,单位分钟')
    movie_state = models.ManyToManyField(MovieCountry, blank=True, verbose_name='电影所属国家', help_text='电影所属国家')
    sub_title = models.ManyToManyField(SubTitle, verbose_name='电影副标题', help_text='电影副标题', blank=True, default="")

    staffs = models.ManyToManyField(MovieStaff, through='MovieAllStaffs', verbose_name='制作人员')
    view_num = models.PositiveIntegerField(default=0, verbose_name='用户浏览数量', help_text='用户浏览数量')
    user_want_num = models.ManyToManyField(User, verbose_name='用户想看', help_text='用户想看', related_name='want_user')

    class Meta:
        verbose_name = '电影信息'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


import uuid
from django.utils.deconstruct import deconstructible
from django.utils.timezone import now
import os


@deconstructible
class UploadToPathAndRename(object):
    def __init__(self, path):
        year = str(now().year)
        month = str(now().month)

        self.sub_path = os.path.join(path, year, month)

    def __call__(self, instance, filename):
        ext = filename.split('.')[-1]
        filename = '{}.{}'.format(uuid.uuid4().hex[:8], ext)
        return os.path.join(self.sub_path, filename)


def test_directory_path(instance, filename, *args):
    ext = filename.split('.')[-1]
    filename = '{}.{}'.format(uuid.uuid4().hex[:8], ext)
    # return the whole path to the file
    return "{0}/{1}/".format("avatar", filename)


class MovieImages(models.Model):
    movie = models.ForeignKey(MovieDetail, verbose_name='剧照对应的电影', help_text='剧照对应的电影')
    image = models.ImageField(upload_to=UploadToPathAndRename("movies"), verbose_name='照片', help_text='照片')
    desc = models.CharField(max_length=20, verbose_name='剧照描述', help_text='剧照描述', blank=True, default="")

    class Meta:
        verbose_name = '电影剧照'
        verbose_name_plural = verbose_name


class MovieAllStaffs(models.Model):
    """
    如马特达蒙本人是导演 编剧 演员
    但是他在谍影重重中 是演员 并不是导演,所以我们需要给在本部电影中给定他的角色
    """
    staff = models.ForeignKey(MovieStaff, verbose_name='职员信息', help_text='职员信息')
    movie = models.ForeignKey(MovieDetail, verbose_name='所属电影', help_text='所属电影', related_name='staffs_in_movie')
    type = models.ForeignKey(MovieStaffCategory, verbose_name='所属类型', help_text='所属类型')

    class Meta:
        verbose_name = '每个电影职员信息'
        verbose_name_plural = verbose_name

        unique_together = ("staff", "movie", "type")


# class UserStarMovie(models.Model):
#     """
#     用户对电影的评分,一个用户可以对多个电影评分,一部电影也可以拥有多个用户的评分,用户评分之后就不能再去评分这个电影了
#     """
#
#     STAR = (
#         ('1', ''),
#         ('2', ''),
#         ('3', ''),
#         ('4', ''),
#         ('5', ''),
#         ('6', ''),
#         ('7', ''),
#         ('8', ''),
#         ('9', ''),
#         ('10', ''),
#     )
#     user = models.ForeignKey(User, verbose_name='评论用户', help_text='评论用户')
#     movie = models.ForeignKey(MovieDetail, verbose_name='所属电影', help_text='所属电影')
#     star = models.CharField(max_length=2, choices=STAR, verbose_name='用户对电影的评分', help_text='用户对电影的评分')
#
#     class Meta:
#         verbose_name = '用户评论一部电影'
#         verbose_name_plural = verbose_name
#
#         unique_together = ("user", "movie")
#
#
# class UserFavMovie(models.Model):
#     """
#     用户点赞一个电影
#     """
#
#     user = models.ForeignKey(User, verbose_name='点赞用户', help_text='点赞用户')
#     movie = models.ForeignKey(MovieDetail, verbose_name='所属电影', help_text='所属电影')
#
#     class Meta:
#         verbose_name = '用户评论一部电影'
#         verbose_name_plural = verbose_name
#
#         unique_together = ("user", "movie")


class CinemaCity(models.Model):
    """
    影院所属城市信息
    """
    name = models.CharField(max_length=40, unique=True, verbose_name='影院所属城市信息名称')
    desc = models.TextField(max_length=150, default="", blank=True, verbose_name='影院所属城市信息简介')

    class Meta:
        verbose_name = "影院所属城市信息"
        verbose_name_plural = verbose_name

    def __str__(self):
        return str(self.name)


class Cinema(models.Model):
    """
    影院信息
    """
    name = models.CharField(max_length=40, unique=True, verbose_name='影院名称')
    desc = models.TextField(max_length=150, default="", verbose_name='影厅简介')
    address = models.CharField(max_length=300, verbose_name='影院地址', blank=True, null=True)
    cinema_city = models.ForeignKey(CinemaCity, blank=True, null=True, verbose_name='影院所属城市')

    class Meta:
        verbose_name = "影院信息"
        verbose_name_plural = verbose_name

    def __str__(self):
        return str(self.name)


class MovieHall(models.Model):
    """
    影厅信息
    """
    name = models.CharField(max_length=40, unique=True, default="", verbose_name='影厅中文名称')
    desc = models.TextField(max_length=150, default="", verbose_name='影厅简介')
    num = models.CharField(max_length=3, unique=True, verbose_name='影厅编号', default='0')
    cinema = models.ForeignKey(Cinema, verbose_name='影院信息', blank=True, null=True)

    class Meta:
        verbose_name = "影厅信息"
        verbose_name_plural = verbose_name
        unique_together = ('name', 'num')

    def __str__(self):
        return self.num


class FilmRowPiece(models.Model):
    """
    排片信息
    """

    movie_name = models.ForeignKey(MovieDetail, verbose_name="电影名称")
    movie_hall = models.ForeignKey(MovieHall, verbose_name="电影播放的影厅")
    start_time = models.DateTimeField(verbose_name="开始播放时间")
    end_time = models.DateTimeField(verbose_name="播放结束时间")
    add_time = models.DateTimeField(verbose_name="信息添加时间", auto_now=True)
    market_price = models.FloatField(default=0, verbose_name='现场价格')
    online_price = models.FloatField(default=0, verbose_name='线上app价格')
    kind = models.ForeignKey(MovieTypeCategory, verbose_name='排片的类型', related_name='row_piece_kind')

    class Meta:
        verbose_name = "排片信息"
        verbose_name_plural = verbose_name
        unique_together = ('movie_name', 'movie_hall', 'start_time', 'end_time')

    def __str__(self):
        return '片场id:{},电影名:{},开始时间:{},结束时间:{}'.format(self.id,self.movie_name.name,self.start_time,self.end_time)

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        # 电影播放结束时间是开始时间加上电影时间
        self.end_time = self.start_time + timedelta(minutes=120)

        # TODO 判断时间是否由冲突
        return super().save(force_insert=force_insert, force_update=force_update, using=using,
                            update_fields=update_fields)


class Seat(models.Model):
    """
    座位信息
    """
    SEAT_TYPE = (
        ('1', '正常座位'),
        ('2', '残疾座位'),
        ('3', '不可以用座位')
    )
    movie_hall = models.ForeignKey(MovieHall, verbose_name='座位所属在大厅', related_name='seats')
    seat_row = models.CharField(max_length=5, verbose_name='座位所在排数', help_text='使用和影厅一样的行标识')
    seat_column = models.CharField(max_length=5, verbose_name='座位座位列数', help_text="'使用和影厅一样的列标识'")
    seat_column_order = models.IntegerField(verbose_name='座位座位列数排序', help_text="座位座位列数排序 从小到大", default=0)
    seat_type = models.CharField(choices=SEAT_TYPE, default='1', max_length=1, verbose_name='座位类型')

    class Meta:
        verbose_name = "座位信息"
        verbose_name_plural = verbose_name
        unique_together = ('movie_hall', 'seat_row', 'seat_column')
        ordering = ['seat_row', 'seat_column_order']

    def __str__(self):
        return "影厅:" + self.movie_hall.num + "-行:" + self.seat_row + "-列:" + self.seat_column


class MoviePieceSeat(models.Model):
    """
    每个片场对应的座位信息
    """

    STATUS = (
        ('0', '还没有人订座'),
        ('1', '锁定中'),
        ('2', '已经售出'),
    )
    seat = models.ForeignKey(Seat, verbose_name='对应片场的座位')
    movie_piece = models.ForeignKey(FilmRowPiece, verbose_name='排片信息', help_text='排片信息',related_name='movie_piece_seat_piece')
    status = models.CharField(max_length=2, choices=STATUS, default='0', verbose_name='片场座位的状态')
    # 如果状态是 1 但是锁定时间超时了 就还是可以去够买
    lock_time = models.DateTimeField(auto_now=True, verbose_name='锁定到期时间', help_text='锁定到期时间')
    owner = models.ForeignKey(User, verbose_name='够买用户', help_text='够买用户', null=True, default=None)

    class Meta:
        verbose_name = '片场对应的座位信息'
        verbose_name_plural = verbose_name

    def __str__(self):

        return str("电影{},片场{},座位 {}排{}列".format(self.movie_piece.movie_name.name,self.movie_piece.id,self.seat.seat_row,self.seat.seat_column))
